package com.cold.demo.web.util;

import java.io.*;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPUtil {
    public static void main(String[] args) throws IOException {
        String dir = "D:/Tools/IdeaIU/IdeaProjects2/demo-project/demo-web/src/main/java/com/example/demo/util";

        String sourceFilePath = Paths.get(dir, "GZIPUtil.java").toString();
        String targetFilePath = Paths.get(dir, "GZIPUtil2.java").toString();
        new File(targetFilePath).delete();

        InputStream inputStream = new FileInputStream(sourceFilePath);

        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(targetFilePath));

        byte[] bytes = new byte[4096];
        int    len;
        while ((len = inputStream.read(bytes)) != -1) {
            gzipOutputStream.write(bytes, 0, len);
        }
        gzipOutputStream.close();
        inputStream.close();
    }




    /**
     * 对该字节数组进行压缩
     * @param sourceBytes 未进行gzip的原始数组
     * @return
     */
    public static byte[] compressByte(byte[] sourceBytes) {
        ByteArrayOutputStream out  = null;
        GZIPOutputStream      gzip = null;
        try {
            out = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(out);
            gzip.write(sourceBytes);
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            close(gzip);
            close(out);
        }
    }


    /**
     * 对该已压缩的字节数组进行解压
     * @param gzipBytes gzip的已压缩数组
     * @return
     */
    public static byte[] unCompressByte(byte[] gzipBytes) {
        ByteArrayOutputStream out = null;
        GZIPInputStream       in  = null;
        try {
            out = new ByteArrayOutputStream();
            in = new GZIPInputStream(new ByteArrayInputStream(gzipBytes));

            byte[] buffer = new byte[4096];
            int    len;
            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            close(out);
            close(in);

        }

    }



    private static void close(Closeable closeable) {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (IOException e) {
        }
    }
}
